<template>
	<div class="w-full">
		<el-form :inline="true" :model="formInline">
			<!-- <el-form-item label="问题">
                <el-input v-model="formInline.question" placeholder="问题" clearable></el-input>
            </el-form-item>
            <el-form-item label="答案">
                <el-input v-model="formInline.answer" placeholder="答案" clearable></el-input>
            </el-form-item> -->
			<el-form-item>
				<el-button @click="init('talk')" :disabled="talkDoing">{{
					!talkDoing ? "训练对话模型" : "对话训练中.."
				}}</el-button>
				<el-button type="primary" @click="delModel('talk')"
					>删除对话模型</el-button
				>
				<el-button @click="init('semantics')" :disabled="semanticsDoing">{{
					!semanticsDoing ? "训练语义模型" : "语义训练中.."
				}}</el-button>
				<el-button type="danger" @click="delModel('semantics')"
					>删除语义模型</el-button
				>
				<el-button type="success" @click="timeoutController">{{
					enableTimeout ? "关闭训练状态刷新" : "开启训练状态刷新"
				}}</el-button>
				<el-divider></el-divider>
				<el-button type="primary" @click="renderData()">刷新数据</el-button>
				<el-button type="success" @click="openDialog()">新增</el-button>
				<el-button type="danger" @click="deleteHandle()">批量删除</el-button>
			</el-form-item>
		</el-form>
		<el-table
			:data="tableData"
			v-loading="dataListLoading"
			@selection-change="selectionChangeHandle"
			:cell-style="statusCellStyle"
			style="width: 100%"
		>
			<el-table-column
				fixed
				type="selection"
				header-align="center"
				align="center"
				width="50"
			>
			</el-table-column>
			<el-table-column
				fixed
				prop="status"
				label="使用状态"
				:formatter="formatterStatus"
			>
			</el-table-column>
			<el-table-column
				prop="showLog"
				label="是否打印训练日志"
				:formatter="formatterLogStatus"
			>
			</el-table-column>
			<el-table-column prop="title" label="标题"> </el-table-column>
			<el-table-column prop="remark" label="备注"> </el-table-column>
			<el-table-column prop="baseDir" label="模型目录"> </el-table-column>
			<el-table-column prop="typeNub" label="语义分类数"> </el-table-column>
			<el-table-column prop="wordVectorDimension" label="语义分类词嵌入维度">
			</el-table-column>
			<el-table-column prop="qaWordVectorDimension" label="问答词嵌入维度">
			</el-table-column>
			<el-table-column prop="maxWordLength" label="用户语句最大长度">
			</el-table-column>
			<el-table-column prop="maxAnswerLength" label="Ai最大回答长度">
			</el-table-column>
			<el-table-column prop="keyWordNerveDeep" label="关键词敏感嗅探颗粒度大小">
			</el-table-column>
			<el-table-column prop="times" label="Qa模型训练增强(times)">
			</el-table-column>
			<el-table-column prop="param" label="正则抑制系数"> </el-table-column>
			<el-table-column prop="trustPowerTh" label="生成语句可信阈值">
			</el-table-column>
			<el-table-column prop="sentenceTrustPowerTh" label="语义分类可信阈值">
			</el-table-column>
			<el-table-column prop="createdTime" label="创建时间" width="180">
			</el-table-column>
			<el-table-column prop="updatedTime" label="更新时间" width="180">
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="140">
				<template #default="scope">
					<el-button
						link
						type="primary"
						size="small"
						@click="use(scope.row.id)"
						v-if="scope.row.status == 0"
						>使用</el-button
					>
					<el-button
						link
						type="warning"
						size="small"
						@click="openDialog(scope.row)"
						>修改</el-button
					>
					<el-button
						link
						type="danger"
						size="small"
						@click="deleteHandle(scope.row.id)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<el-affix position="bottom" :offset="60" class="mt-4">
			<el-pagination
				class="mt-2"
				size="small"
				v-model:current-page="formInline.current"
				v-model:page-size="formInline.size"
				:page-sizes="[15, 20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</el-affix>
	</div>
	<el-dialog
		title="添加或修改"
		v-model="dialogFormVisible"
		:width="dialogWidth"
	>
		<el-form
			:model="formDialog"
			class="demo-form-inline"
			ref="formRef"
			:inline="true"
			label-position="top"
		>
			<el-form-item label="标题" prop="typeNub">
				<el-input v-model="formDialog.title" placeholder="标题"></el-input>
			</el-form-item>
			<el-form-item label="备注" prop="typeNub">
				<el-input v-model="formDialog.remark" placeholder="备注"></el-input>
			</el-form-item>
			<el-form-item label="模型目录" prop="baseDir">
				<el-input
					v-model="formDialog.baseDir"
					placeholder="模型目录"
				></el-input>
			</el-form-item>
			<el-form-item label="语义分类种类数" prop="typeNub">
				<el-input
					v-model="formDialog.typeNub"
					placeholder="语义分类种类数"
				></el-input>
			</el-form-item>
			<el-form-item label="语义分类词嵌入维度" prop="wordVectorDimension">
				<el-input
					v-model="formDialog.wordVectorDimension"
					placeholder="语义分类词嵌入维度"
				></el-input>
			</el-form-item>
			<el-form-item label="问答词嵌入维度" prop="qaWordVectorDimension">
				<el-input
					v-model="formDialog.qaWordVectorDimension"
					placeholder="问答词嵌入维度"
				></el-input>
			</el-form-item>
			<el-form-item label="用户语句最大长度" prop="maxWordLength">
				<el-input
					v-model="formDialog.maxWordLength"
					placeholder="用户语句最大长度"
				></el-input>
			</el-form-item>
			<el-form-item label="Ai最大回答长度" prop="maxAnswerLength">
				<el-input
					v-model="formDialog.maxAnswerLength"
					placeholder="Ai最大回答长度"
				></el-input>
			</el-form-item>
			<el-form-item label="关键词敏感嗅探颗粒度" prop="keyWordNerveDeep">
				<el-input
					v-model="formDialog.keyWordNerveDeep"
					placeholder="关键词敏感嗅探颗粒度"
				></el-input>
			</el-form-item>
			<el-form-item label="Qa模型训练增强" prop="times">
				<el-input
					v-model="formDialog.times"
					placeholder="Qa模型训练增强"
				></el-input>
			</el-form-item>
			<el-form-item label="正则抑制系数" prop="times">
				<el-input
					v-model="formDialog.param"
					placeholder="正则抑制系数"
				></el-input>
			</el-form-item>
			<el-form-item label="生成语句可信阈值" prop="times">
				<el-input
					v-model="formDialog.trustPowerTh"
					placeholder="生成语句可信阈值"
				></el-input>
			</el-form-item>
			<el-form-item label="语义分类可信阈值" prop="times">
				<el-input
					v-model="formDialog.sentenceTrustPowerTh"
					placeholder="语义分类可信阈值"
				></el-input>
			</el-form-item>
			<el-form-item label="minLength" prop="minLength">
				<el-input
					v-model="formDialog.minLength"
					placeholder="minLength"
				></el-input>
			</el-form-item>
			<el-form-item label="weStudyPoint" prop="weStudyPoint">
				<el-input
					v-model="formDialog.weStudyPoint"
					placeholder="weStudyPoint"
				></el-input>
			</el-form-item>
			<el-form-item label="weLParam" prop="weLParam">
				<el-input
					v-model="formDialog.weLParam"
					placeholder="weLParam"
				></el-input>
			</el-form-item>
			<el-form-item label="控制台打印训练日志" prop="showLog">
				<el-select v-model="formDialog.showLog">
					<el-option label="是" :value="1"></el-option>
					<el-option label="否" :value="0"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button
					@click="Object.assign(formDialog, defaultValue)"
					v-if="defaultFull == true"
					type="success"
					>填充默认</el-button
				>
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button
					type="primary"
					@click="addOrUpdateHandle"
					:loading="!dialogFormVisible"
					:loading-icon="loading"
					>确 定</el-button
				>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	const tableData = ref([]);
	const total = ref(0);
	const formInline = ref({
		current: 1,
		size: 15,
		answer: "",
		question: "",
	});
	const talkDoing = ref(false);
	const semanticsDoing = ref(false);

	const model = reactive({
		id: "",
		title: "",
		remark: "",
		baseDir: "",
		typeNub: "",
		wordVectorDimension: "",
		qaWordVectorDimension: "",
		maxWordLength: "",
		maxAnswerLength: "",
		keyWordNerveDeep: "",
		times: "",
		param: "",
		trustPowerTh: "",
		sentenceTrustPowerTh: "",
		minLength: "",
		weStudyPoint: "",
		weLParam: "",
		showLog: 0,
	});
	const defaultValue = reactive({
		title: "default",
		remark: "default",
		baseDir: "D:\\testModel\\",
		typeNub: "11",
		wordVectorDimension: "21",
		qaWordVectorDimension: "32",
		maxWordLength: "20",
		maxAnswerLength: "30",
		keyWordNerveDeep: "3",
		times: "1",
		param: "0.3",
		trustPowerTh: "0",
		sentenceTrustPowerTh: "0.3",
		minLength: 5,
		weStudyPoint: 0.05,
		weLParam: 0.001,
		showLog: 0,
	});
	const formDialog = reactive({ ...model });
	const formRef = ref(null);
	const dataListLoading = ref(false);
	const dataListSelections = ref([]);
	const dialogFormVisible = ref(false);
	const defaultFull = ref(true);

	const formatterStatus = (row) => {
		return row.status == 1 ? "是" : "否";
	};
	const formatterLogStatus = (row) => {
		return row.showLog == 1 ? "是" : "否";
	};
	//设置字体颜色
	const statusCellStyle = (row, column, rowIndex, columnIndex) => {
		if (row.column.label == "使用状态") {
			if (row.row.status == 1) {
				return { color: "var(--el-color-success)" };
			} else {
				return { color: "var(--el-color-error)" };
			}
		} else if (row.column.label == "是否打印训练日志") {
			if (row.row.showLog == 1) {
				return { color: "var(--el-color-success)" };
			} else {
				return { color: "var(--el-color-error)" };
			}
		}
	};
	const timeoutId = ref(null);
	const enableTimeout = ref(true);
	const dialogWidth = ref("300px");
	const startTimer = () => {
		// 设置新的定时器
		timeoutId.value = setInterval(() => {
			renderStatus();
		}, 1000 * 3);
	};
	const timeoutController = () => {
		if (timeoutId.value && enableTimeout.value) {
			clearInterval(timeoutId.value);
			ElMessage.success("关闭成功");
		} else {
			startTimer();
			ElMessage.success("开启成功");
		}
		enableTimeout.value = !enableTimeout.value;
	};

	//挂载页面
	onMounted(() => {
		renderData();
		window.addEventListener("resize", resize(dialogWidth, 220, 420, 840));
		nextTick(() => {
			if (timeoutId.value) {
				clearInterval(timeoutId.value);
			}
			startTimer();
		});
	});
	const renderStatus = () => {
		status("talk");
		status("semantics");
	};
	const handleSizeChange = (newSize: number) => {
		formInline.size = newSize;
		renderData();
	};
	const handleCurrentChange = (newPage: number) => {
		if (!newPage) {
			return;
		}
		formInline.current = newPage;
		renderData();
	};
	// 获取数据列表
	const renderData = async () => {
		dataListLoading.value = true;
		await pageConfig(formInline.value).then((res) => {
			tableData.value = [];
			if (res.value.error === 0) {
				total.value = res.value.data.total;
				tableData.value = res.value.data.records;
			}
			dataListLoading.value = false;
		});
		renderStatus();
	};
	// 多选
	const selectionChangeHandle = (val) => {
		dataListSelections.value = val;
	};

	const openDialog = (row) => {
		dialogFormVisible.value = true;
		if (row) {
			//update
			defaultFull.value = false;
			Object.assign(formDialog, row);
		} else {
			//add
			defaultFull.value = true;
			Object.assign(formDialog, model);
		}
	};
	// 新增 / 修改
	const addOrUpdateHandle = (row) => {
		saveConfig(formDialog).then(async (res) => {
			if (res.value.error === 0) {
				ElMessage.success("操作成功");
				dialogFormVisible.value = false;
				renderData();
			} else if (res.value.error === 400) {
				ElMessage.error(res.value.errorMessage);
			} else {
				ElMessage.error("操作失败");
			}
		});
	};

	const init = (typ) => {
		initModel({
			type: typ,
		}).then(async (res) => {
			if (res.value.error === 0) {
				ElMessage.success("训练中");
				status(typ);
			} else {
				ElMessage.error(res.value.errorMessage);
			}
		});
	};

	const delModel = (typ) => {
		ElMessageBox.confirm("确认删除嘛？", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			deleteModel({
				type: typ,
			}).then((res) => {
				if (res.value.error === 0) {
					ElMessage.success("删除成功");
					renderStatus();
				} else {
					ElMessage.error("模型不存在或已删除");
				}
			});
		});
	};
	const status = (typ) => {
		getStatus({
			type: typ,
		}).then(async (res) => {
			if (res.value.error === 0) {
				if (typ === "talk") {
					talkDoing.value = res.value.data;
				} else {
					semanticsDoing.value = res.value.data;
				}
			}
		});
	};
	// 删除
	const deleteHandle = (id) => {
		var ids = id
			? [id]
			: dataListSelections.value.map((item) => {
					return item.id;
			  });
		ElMessageBox.confirm(
			`确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
			"提示",
			{
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}
		).then(() => {
			deleteConfig({ ids: ids }).then(async (res) => {
				if (res.value.error === 0) {
					ElMessage.success("删除成功");
					renderData();
				} else {
					ElMessage.error("删除失败");
				}
			});
		});
	};

	const use = (id) => {
		ElMessageBox.confirm("使用当前记录作为训练模型参数", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			useConfig({ id: id }).then(async (res) => {
				if (res.value.error === 0) {
					ElMessage.success("操作成功");
					renderData();
				} else {
					ElMessage.error("操作失败");
				}
			});
		});
	};
</script>

<style>
	.demo-form-inline .el-input {
		--el-input-width: 156px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 156px;
	}
</style>